# -*- coding;utf-8 -*-
"""
File name : latext2Docx.PY
Program IDE : PyCharm
Create file time: 2024/7/20 15:09
File Create By Author : 朱清闯
"""
import latex2mathml.converter
from docx import Document
from lxml import etree
import re
import xml.dom.minidom as xdom


def mathml2str(mathml_doc):
    return etree.tostring(mathml_doc, pretty_print=True, xml_declaration=True, encoding='UTF-8')


def exist_latex(latex_str: str):
    pattern = r'\$\$.+\$\$'
    return re.search(pattern, latex_str)


def latex_to_mathml(latex_str: str):
    """
    latex 转成 mathml表达式
    :param latex_str: latex字符串
    :return: mathml表达式
    """
    mathml_result = latex2mathml.converter.convert(latex_str)
    print('mathml_result:', mathml_result)
    return mathml_result


# xslt = xdom.parse('word/MML2OMML.XSL')
xslt = etree.parse('word/MML2OMML.XSL')
xslt_transform = etree.XSLT(xslt)


def mathml_to_oxml(mathml_str: str):
    """
    mathml表达式 转换成word的oxml
    :param mathml_str: mathml表达式
    :return: word的oxml dom
    """
    dom = etree.fromstring(mathml_str)
    transform = etree.XSLT(xslt)
    new_dom = transform(dom).getroot()
    print('omxl result:', new_dom)
    return new_dom
    # return xslt_transform(mathml_xml).getroot()


def latex_to_oxml(latex_str: str):
    mathml_str = latex_to_mathml(latex_str)
    return mathml_to_oxml(mathml_str)


def main(latex_str=r'\frac{\frac{a}{c}}{b}\times', file_path='example.docx'):
    # 创建一个新的 Word 文档
    doc = Document()
    # 添加一个段落
    paragraph = doc.add_paragraph()
    # 创建一个 run 对象
    run = paragraph.add_run()
    run._element.append(latex_to_oxml(latex_str))
    # 保存文档
    doc.save(file_path)
    return True


# if __name__ == '__main__':
#     latex_str = r'\frac{\frac{a}{c}}{b}\times d\%'
#     # 创建一个新的 Word 文档
#     doc = Document()
#     # 添加一个段落
#     paragraph = doc.add_paragraph()
#     # 创建一个 run 对象
#     run = paragraph.add_run()
#     run._element.append(latex_to_oxml(latex_str))
#     # 保存文档
#     doc.save('example.docx')
